package com.canaan.business.controller.pc.bill;

import cn.hutool.core.lang.Pair;
import cn.hutool.json.JSONUtil;
import com.canaan.business.common.enums.inOutStock.ErpBillTypeEnum;
import com.canaan.business.common.enums.inOutStock.OutOrderStatusEnum;
import com.canaan.business.domain.bill.*;
import com.canaan.business.domain.inOutStock.OutStockBillDetail;
import com.canaan.business.domain.vo.*;
import com.canaan.business.service.bill.IAdjustOutBillService;
import com.canaan.business.service.bill.IPurchaseReturnBillDetailService;
import com.canaan.business.service.bill.IPurchaseReturnBillService;
import com.canaan.common.annotation.Log;
import com.canaan.common.core.controller.BaseController;
import com.canaan.common.core.domain.AjaxResult;
import com.canaan.common.core.page.TableDataInfo;
import com.canaan.common.encrypt.PushEdiService;
import com.canaan.common.enums.BusinessType;
import com.canaan.common.utils.DateUtils;
import com.canaan.common.utils.StringUtils;
import com.canaan.common.utils.poi.ExcelUtil;
import com.canaan.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购退货单Controller
 *
 * @author ruoyi
 * @date 2023-03-13
 */
@Api(tags = "采购退货单")
@RestController
@RequestMapping("/bill/purchaseReturn")
public class PurchaseReturnBillController extends BaseController {
    @Resource
    private IPurchaseReturnBillService purchaseReturnBillService;
    @Resource
    private IPurchaseReturnBillDetailService purchaseReturnBillDetailService;

    @Resource
    private IAdjustOutBillService adjustOutBillService;
    @Resource
    private ISysConfigService sysConfigService;
    /**
     * 查询采购退货单列表
     */
    @ApiOperation(value = "查询采购退货单列表")
    @GetMapping("/list")
    public TableDataInfo list(PurchaseReturnBill purchaseReturnBill) {
        startPage();
        List<PurchaseReturnBill> list = purchaseReturnBillService.selectPurchaseReturnBillList(purchaseReturnBill);
        return getDataTable(list);
    }

    /**
     * 导出采购退货单列表
     */
    @ApiOperation(value = "导出采购退货单列表")
    @Log(title = "采购退货单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PurchaseReturnBill purchaseReturnBill) {
        List<PurchaseReturnBillExportVo> list = purchaseReturnBillService.exportList(purchaseReturnBill);
        ExcelUtil<PurchaseReturnBillExportVo> util = new ExcelUtil<PurchaseReturnBillExportVo>(PurchaseReturnBillExportVo.class);
        util.exportExcel(response, list, "采购退货单数据");
    }

    /**
     * 获取采购退货单详细信息
     */
    @ApiOperation(value = "获取采购退货单详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(purchaseReturnBillService.selectPurchaseReturnBillById(id));
    }

    /**
     * 新增采购退货单
     */
    @ApiOperation(value = "新增采购退货单")
    @Log(title = "采购退货单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PurchaseReturnBill purchaseReturnBill) {
        return toAjax(purchaseReturnBillService.insertPurchaseReturnBill(purchaseReturnBill));
    }

    /**
     * 修改采购退货单
     */
    @ApiOperation(value = "修改采购退货单")
    @Log(title = "采购退货单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PurchaseReturnBill purchaseReturnBill) {
        return toAjax(purchaseReturnBillService.updatePurchaseReturnBill(purchaseReturnBill));
    }

    /**
     * 删除采购退货单
     */
    @ApiOperation(value = "删除采购退货单")
    @Log(title = "采购退货单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(purchaseReturnBillService.deletePurchaseReturnBillByIds(ids));
    }

    /**
     * 确认取消
     */
    @ApiOperation(value = "确认取消")
    @Log(title = "采购退货单", businessType = BusinessType.UPDATE)
	@PutMapping("/confirmCancel")
    public AjaxResult confirmCancel(@RequestBody PurchaseReturnBill purchaseReturnBill) {
        return toAjax(purchaseReturnBillService.confirmCancel(purchaseReturnBill));
    }

    @ApiOperation(value = "采购退货单执行")
    @Log(title = "采购退货单执行", businessType = BusinessType.UPDATE)
    @PostMapping("/execute")
    @Transactional
    public AjaxResult execute(@RequestBody List<PurchaseReturnBill> purchaseReturnBills) {
        if(purchaseReturnBills==null|| purchaseReturnBills.size()==0){
            return error("库采购退货单数据为空");
        }
        for (PurchaseReturnBill item : purchaseReturnBills){
            PurchaseReturnBill data=purchaseReturnBillService.selectPurchaseReturnBillByNo(item.getNo());
            if(data==null){
                return error("采购退货单"+item.getNo()+"数据不存在");
            }
            if(OutOrderStatusEnum.NEW.getCode().equals(data.getStatus())) {
                purchaseReturnDispatcher(data);
            }
            else if(OutOrderStatusEnum.WAITING_PICK.getCode().equals(data.getStatus())){
                prePickOutBillDispatcher(data);
            }
        }
        return toAjax(1);
    }

    /**
     *  采购退货单分配
     */
    private void purchaseReturnDispatcher(PurchaseReturnBill purchaseReturnBill){
        //查询调拨出库单明细
        List<String> productNos=new ArrayList<>();
        List<Long> productCounts=new ArrayList<>();
        List<String> batchNos=new ArrayList<>();
        String stockStatus=purchaseReturnBill.getStockStatus();
        PurchaseReturnBillDetail query=new PurchaseReturnBillDetail();
        query.setOrderNo(purchaseReturnBill.getNo());
        query.setDelFlag("0");
        List<PurchaseReturnBillDetail> details=purchaseReturnBillDetailService.selectPurchaseReturnBillDetailList(query);
        for (PurchaseReturnBillDetail detail :details){
            productNos.add(detail.getProductNo());
            productCounts.add(detail.getOrderQty());
            if(StringUtils.isEmpty(detail.getBatchNo())){
                batchNos.add("");
            }else{
                batchNos.add(detail.getBatchNo());
            }
        }
        //OutStockQueryVo赋值
        OutStockQueryVo outStockQueryVo=new OutStockQueryVo();
        outStockQueryVo.setStockStatus(stockStatus);
        outStockQueryVo.setProductNos(productNos);
        outStockQueryVo.setProductCounts(productCounts);
        outStockQueryVo.setBatchNos(batchNos);
        outStockQueryVo.setBillNo(purchaseReturnBill.getNo());
        outStockQueryVo.setBillType(ErpBillTypeEnum.PURCHASE_RETURN.getCode());
        outStockQueryVo.setCellCode(purchaseReturnBill.getCellCode());
        OutStockResultVo outStockResultVo=adjustOutBillService.analyseOutStock(outStockQueryVo);
        for (PurchaseReturnBillDetail item:details) {
            List<OutStockBillDetail> outStockBillDetails =outStockResultVo.getOutStockBillDetails().stream().filter(O->O.getProductNo().equals(item.getProductNo())).collect(Collectors.toList());
            if(outStockBillDetails.size() != 0){
                OutStockBillDetail outStockBillDetail=outStockBillDetails.get(0);
                item.setBatchNo(outStockBillDetail.getBatchNo());
            }
        }
        purchaseReturnBillDetailService.batchUpdatePurchaseReturnBillDetail(details);
        purchaseReturnBill.setStatus(OutOrderStatusEnum.PICKING.getCode());
        purchaseReturnBillService.updatePurchaseReturnBill(purchaseReturnBill);
        adjustOutBillService.postOutStockCallback(purchaseReturnBill.getNo(),
                purchaseReturnBill.getStockStatus());
    }
    /**
     * 预选出库单分配
     */
    public void prePickOutBillDispatcher(PurchaseReturnBill purchaseReturnBill){
        PurchaseReturnBillDetail query=new PurchaseReturnBillDetail();
        query.setOrderNo(purchaseReturnBill.getNo());
        query.setDelFlag("0");
        List<PurchaseReturnBillDetail> details=purchaseReturnBillDetailService.selectPurchaseReturnBillDetailList(query);
        OutStockResultVo outStockResultVo= adjustOutBillService.handlePreOutStockBill(purchaseReturnBill.getNo(),ErpBillTypeEnum.PURCHASE_RETURN.getCode(),purchaseReturnBill.getCellCode());
        for (PurchaseReturnBillDetail item:details) {
            List<OutStockBillDetail> outStockBillDetails =outStockResultVo.getOutStockBillDetails().stream().filter(O->O.getProductNo().equals(item.getProductNo())).collect(Collectors.toList());
            if(outStockBillDetails.size() != 0){
                OutStockBillDetail outStockBillDetail=outStockBillDetails.get(0);
                item.setBatchNo(outStockBillDetail.getBatchNo());
            }
        }
        purchaseReturnBillDetailService.batchUpdatePurchaseReturnBillDetail(details);
        purchaseReturnBill.setStatus(OutOrderStatusEnum.PICKING.getCode());
        purchaseReturnBillService.updatePurchaseReturnBill(purchaseReturnBill);
        adjustOutBillService.postOutStockCallback(purchaseReturnBill.getNo(), purchaseReturnBill.getStockStatus());
        logger.info("出库成功：{}", purchaseReturnBill);
    }
}
